package com.tanhua.sso.server.service;



import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tanhua.api.*;
import com.tanhua.autoconfig.tmplate.AipTemplate;
import com.tanhua.autoconfig.tmplate.OssTemplate;
import com.tanhua.config.UserHolder;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.result.Result;
import com.tanhua.sso.pojo.*;
import com.tanhua.sso.vo.BlacklistVo;
import com.tanhua.sso.vo.SettingsVo;
import com.tanhua.sso.vo.TypeVo;
import com.tanhua.sso.vo.UserInfoVo;

import com.tanhua.util.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
public class UsersService {

    @DubboReference
    private UserInfoService userInfoService;

    @DubboReference
    private UserLikeServiceApi userLikeServiceApi;

    @DubboReference
    private RecommendUserService recommendUserService;

    @DubboReference
    private FocusUserServiceApi focusUserServiceApi;

    @DubboReference
    private VisitorsServiceApi visitorsServiceApi;

    @DubboReference
    private UserService userService;

    @Autowired
    private MessagesService messagesService;

    @Autowired
    private OssTemplate ossTemplate;

    @Autowired
    private AipTemplate aipTemplate;

    @DubboReference
    private SettingsServiceApi settingsServiceApi;

    @DubboReference
    private QuestionService questionService;

    @DubboReference
    private BlacklistServiceApi blacklistServiceApi;



    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    public UserInfoVo users(Long userId) {
        //没有id,查询别人
        if (ObjectUtil.isEmpty(userId)){
            Long myId = UserHolder.getUserId();
            UserInfoVo selectUser = userInfoService.select(myId);
            if (ObjectUtil.isEmpty(selectUser)){
                throw new CustomException("查无信息");
            }else {
                return selectUser;
            }
        }
        //有id查询的是自己
        UserInfoVo userInfoVoser = userInfoService.select(userId);
        if (ObjectUtil.isEmpty(userInfoVoser)){
            throw new CustomException("查无信息");
        }else {
            return userInfoVoser;
        }
    }

    //修改用户信息
    public void update(UserInfo userInfo) {
        //设置id
        Long userId = UserHolder.getUserId();
        userInfo.setId(userId);
        //修改
        userInfoService.updateUserinfoVo(userInfo);
    }

    /*互相喜欢、喜欢、粉丝、谁看过我 - 翻页列表
  * type:   1 互相喜欢
            2 我喜欢
            3 粉丝
            4 谁看过我*/
    public Result type(Integer type, Integer page, Integer pagesize, String nickname) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        List<Long> ids=new ArrayList<>();
        //相互喜欢
        if (type==1){
            //查看我喜欢的人
            List<UserLike> likes=userLikeServiceApi.likeAll(userId);
            //获取他们的id
            List<Long> listLikeId = likes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
            for (Long aLong : listLikeId) {
                //判断她是否喜欢我
                boolean apiLike = userLikeServiceApi.isLike(userId, aLong, true);
                if (apiLike){
                    ids.add(aLong);
                }
            }
            //我欢喜的人
        }else if (type==2){
            List<UserLike> likes = userLikeServiceApi.likeAll(userId);
            ids= likes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
            //我的粉丝
        }else if (type==3){
            List<FocusUser> focusUserList=focusUserServiceApi.selectAll(userId);
            ids= focusUserList.stream().map(FocusUser::getFollowUserId).collect(Collectors.toList());
        }else {
            List<Visitors> visitorsList=visitorsServiceApi.myVisitorUserId(userId);
            ids=visitorsList.stream().map(Visitors::getVisitorUserId).collect(Collectors.toList());
        }
        //分页查询用户信息
        Page<UserInfo> userInfoPage = userInfoService.page(page, pagesize, nickname, ids);
        List<UserInfo> records = userInfoPage.getRecords();
        List<TypeVo> typeVoList=new ArrayList<>();
        for (UserInfo record : records) {
            TypeVo typeVo=new TypeVo();
            Long id = record.getId();
            RecommendUser recommendUser = recommendUserService.selectOne(id, userId);
            //设置缘分值
            if (ObjectUtil.isNotEmpty(recommendUser)){
                typeVo.setMatchRate(Convert.toInt(recommendUser.getScore()));
                //随机缘分值
            }else {
                typeVo.setMatchRate(RandomUtil.randomInt(30,99));
            }
            //相互喜欢
            if (type==1){
                typeVo.setAlreadyLove(true);
                //我喜欢的人
                //喜欢的粉丝
            }else if (type==2||type==3){
                boolean apiLike = userLikeServiceApi.isLike(record.getId(),userId, true);
                //设置喜欢她
                if (apiLike){
                    typeVo.setAlreadyLove(true);
                }
            }
            UserInfo userInfo = userInfoService.selectUser(record.getId());
            BeanUtils.copyProperties(userInfo,typeVo);
            typeVo.setId(Convert.toInt(userInfo.getId()));
            typeVoList.add(typeVo);
        }
        Integer count = Convert.toInt(userInfoPage.getTotal());
        int pages=(count/pagesize)+1;
        return new Result(count,pagesize,pages,page,typeVoList);
    }

    //互相喜欢，喜欢，粉丝 - 统计
    public Map count() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看互相喜欢的数目
        //查看我喜欢的人
        List<UserLike> likes=userLikeServiceApi.likeAll(userId);
        //获取他们的id
        List<Long> listLikeId = likes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        List<Long> eachLoveCount=new ArrayList<>();
        for (Long aLong : listLikeId) {
            //判断她是否喜欢我
            boolean apiLike = userLikeServiceApi.isLike(userId, aLong, true);
            if (apiLike){
                eachLoveCount.add(aLong);
            }
        }
        //我喜欢的数目
        List<UserLike> userLikeList = userLikeServiceApi.likeAll(userId);
        List<Long> loveCount = likes.stream().map(UserLike::getLikeUserId).collect(Collectors.toList());
        //粉丝数目
        List<FocusUser> focusUserList=focusUserServiceApi.selectAll(userId);
        List<Long> fanCount = focusUserList.stream().map(FocusUser::getFollowUserId).collect(Collectors.toList());
        Map map=new HashMap();
        map.put("eachLoveCount",eachLoveCount.size());
        map.put("loveCount",loveCount.size());
        map.put("fanCount",fanCount.size());
        return map;
    }

    /*发送手机验证码*/
    public void sendVerificationCode() {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //判断redis中是否存在验证码
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + userId);
        if (StrUtil.isNotEmpty(code)){
            throw new CustomException("验证码未失效");
        }
        String newCode = RandomUtil.randomNumbers(6);
        //存入redis,设置五分钟有效期
        redisTemplate.opsForValue().set(Constants.SMS_CODE+userId,newCode,5, TimeUnit.MINUTES);
        log.error("{验证码为}"+newCode);
    }

    /*校验验证码*/
    public boolean checkVerificationCode(String verificationCode) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //从redis中查找验证码
        String code = redisTemplate.opsForValue().get(Constants.SMS_CODE + userId);
        if (StrUtil.isEmpty(code)){
            throw new CustomException("验证码不存在,或已过期");
        }
        //验证正确
        if (StrUtil.equals(verificationCode,code)){
            //删除缓存
            redisTemplate.delete(Constants.SMS_CODE + userId);
            return true;
        }
        //失败
        return false;
    }

    /*修改手机号*/
    public void setPhone(String phone) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //修改手机号
        userService.selectPhone(userId,phone);
    }

    /*粉丝喜欢*/
    public void fans(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        userLikeServiceApi.save(userId,uid,true);
        //如果他也喜欢我,加好友
        boolean apiLike = userLikeServiceApi.isLike(userId, uid, true);
        if (apiLike){
            messagesService.contacts(uid);
        }
    }


    /*取消喜欢*/
    public void unLike(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        userLikeServiceApi.save(userId,uid,false);
        //删除好友
        messagesService.deleteFriend(uid);
    }

    /*更新头像*/
    public void updateHeader(MultipartFile headPhoto) throws IOException {
        //传入文件名和输入流
        String upload = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        boolean detect = aipTemplate.detect(upload);
        if (!detect){
            throw new CustomException("不包含人脸");
        }else {
            //图片地址更新
            UserInfo userInfo=new UserInfo();
            Long userId = UserHolder.getUserId();
            userInfo.setId(userId);
            userInfo.setAvatar(upload);
            userInfoService.update(userInfo);
        }
    }

    public SettingsVo settings() {
        SettingsVo settingsVo=new SettingsVo();
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看设置
        Settings settings=settingsServiceApi.selectById(userId);
        if (ObjectUtil.isEmpty(settings)){
            throw new CustomException("查无信息");
        }
        //查看问题
        Question byId = questionService.findById(userId);
        //设置问题
        settingsVo.setStrangerQuestion("你喜欢Java吗");
        if (ObjectUtil.isNotEmpty(byId)){
            settingsVo.setStrangerQuestion(byId.getTxt());
        }
        //推送公告通知
        if (settings.getGonggaoNotification()==1){
            settingsVo.setGonggaoNotification(true);
        }
        //推送喜欢通知
        if (settings.getLikeNotification()==1){
            settingsVo.setLikeNotification(true);
        }
        //推送评论通知
        if (settings.getPinglunNotification()==1){
            settingsVo.setPinglunNotification(true);
        }
        settingsVo.setId(Convert.toInt(userId));
        settingsVo.setPhone(UserHolder.getMobile());
        return settingsVo;
    }


    /*保存陌生人问题*/
    public void questions(String content) {
        try {
            //获取当前用户id
            Long userId = UserHolder.getUserId();
            //查看当前用户是否设置过问题
            Question question = questionService.findById(userId);
            //修改问题
            if (ObjectUtil.isNotEmpty(question)){
                question.setTxt(content);
                question.setUpdated(new Date());
                questionService.update(question);
                //保存
            }else {
                 Question newQuestion=new Question();
                 newQuestion.setTxt(content);
                 newQuestion.setUserId(userId);
                 newQuestion.setUpdated(new Date());
                 newQuestion.setCreated(new Date());
                 questionService.save(newQuestion);
            }
        } catch (Exception e) {
            throw new CustomException("陌生人问题设置失败");
        }
    }


    /*通知保存*/
    public void setting(Boolean likeNotification, Boolean pinglunNotification, Boolean gonggaoNotification) {
        try {
            Integer likeNotificationCode=1;
            Integer pinglunNotificationCode=1;
            Integer gonggaoNotificationCode=1;
            //获取当前用户id
            Long userId = UserHolder.getUserId();
            if (!likeNotification){
               likeNotificationCode=0;
            }
            if (!pinglunNotification){
                pinglunNotificationCode=0;
            }
            if (!gonggaoNotification){
                gonggaoNotificationCode=0;
            }
            //查看是否有过设置
            Settings settings = settingsServiceApi.selectById(userId);
            //修改设置
            if (ObjectUtil.isNotEmpty(settings)){
                settings.setLikeNotification(likeNotificationCode);
                settings.setGonggaoNotification(gonggaoNotificationCode);
                settings.setPinglunNotification(pinglunNotificationCode);
                settingsServiceApi.update(settings);
                //保存设置
            }else {
                Settings newSettings=new Settings();
                newSettings.setUserId(userId);
                newSettings.setGonggaoNotification(gonggaoNotificationCode);
                newSettings.setPinglunNotification(pinglunNotificationCode);
                newSettings.setLikeNotification(likeNotificationCode);
                settingsServiceApi.save(newSettings);
            }
        } catch (Exception e) {
            throw new CustomException("设置保存失败");
        }
    }


    /*黑名单列表*/
    public Result blacklist(Integer page, Integer pagesize) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //分页查看黑名单
        Page<BlackList> newPage=blacklistServiceApi.page(userId,page,pagesize);
        List<BlackList> records = newPage.getRecords();
        //收集黑名单id
        List<Long> list = records.stream().map(BlackList::getBlackUserId).collect(Collectors.toList());
        List<BlacklistVo> blacklistVos=new ArrayList<>();
        for (Long aLong : list) {
            UserInfo userInfo = userInfoService.selectUser(aLong);
            if (ObjectUtil.isNotEmpty(userInfo)){
                BlacklistVo blacklistVo=new BlacklistVo();
                blacklistVo.setAge(userInfo.getAge());
                blacklistVo.setGender(userInfo.getGender());
                blacklistVo.setNickname(userInfo.getNickname());
                blacklistVo.setAvatar(userInfo.getAvatar());
                blacklistVo.setId(aLong);
                blacklistVos.add(blacklistVo);
            }
        }
        Integer pages=(blacklistVos.size()/pagesize)+1;
        return new Result(Convert.toInt(newPage.getTotal()),pagesize,pages,page,blacklistVos);
    }


    /*移除黑名单*/
    public void delectBlackList(Long uid) {
        blacklistServiceApi.delectBlackList(UserHolder.getUserId(),uid);
    }


    /*是否喜欢*/
    public boolean alreadyLove(Long uid) {
        //获取当前用户id
        Long userId = UserHolder.getUserId();
        //查看是否喜欢
        boolean apiLike = userLikeServiceApi.isLike(uid, userId, true);
        if (apiLike){
            return true;
        }
        return false;

    }
}


